package com.yjc.dp;

/**
 * 获取两个字符串中最大相同子串
 *
 * @author yjc
 * @create 2024-09-05 14:00
 */
public class Subject_16 {

    public static void main(String[] args) {

        String str1 = "abcwerthelloyuiodef";
        String str2 = "cvhellobnm";

        long start = System.currentTimeMillis();
        for (int i = 0; i < 10000; i++) {
            getMaxStr(str1, str2);
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);

    }

    public static void getMaxStr(String str1, String str2) {
        int[][] dp = new int[str1.length() + 1][str2.length() + 1];

        for (int i = 1; i <= str1.length(); i++) {
            for (int j = 1; j <= str2.length(); j++) {
                if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = 0;
                }
            }
        }

        int maxLen = 0;
        int maxIndex = 0;

        for (int i = 1; i <= str1.length(); i++) {
            for (int j = 1; j <= str2.length(); j++) {
                if (dp[i][j] > maxLen) {
                    maxLen = dp[i][j];
                    maxIndex = i;
                }
            }
        }

        String commonSubStr = str1.substring(maxIndex - maxLen, maxIndex);
//        System.out.println("最大公共子串为：" + commonSubStr);
    }
}
